package com.vancouver.knows.ui.activity.userpost;

import android.animation.Animator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.LoadableList;
import com.pangu.util.StringUtil;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.FilterArgs;
import com.vancouver.knows.business.bean.UserPostInfo;
import com.vancouver.knows.ui.activity.TutorialActivity;
import com.vancouver.knows.ui.activity.citynews.CityNewsCommentsActivity;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.activity.search.NewSearchActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.view.compactcalendarview.AnimatorListener;
import com.vancouver.knows.util.AnalyticsConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-07-12.
 */
public class UserPostActivity extends BaseActivity implements IResultReceiver, View.OnClickListener, UserPostListView.OnFilterSelectedListener, LoadableList.LoadableListScrollListener {

    @Bind(R.id.userpost_layout)
    RelativeLayout mRelativeLayout;
    @Bind(R.id.filter_icon)
    ImageView mFilterIcon;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;

    private RelativeLayout loadingViewForSwitchCategory;

    private UserPostPullRefreshView mController;
    private ImageView mAddPostButton;
    private CreateUserPostCategoryView mCreateUserPostCategoryView;

    private boolean mAddPostFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userpost);

        mController = new UserPostPullRefreshView(this);
        mController.loadData();
        mController.setScrollListener(this);

        RelativeLayout.LayoutParams controllerLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        controllerLayoutParams.addRule(RelativeLayout.BELOW, R.id.toolbar);
        mController.setLayoutParams(controllerLayoutParams);
        mRelativeLayout.addView(mController);

        if (!StringUtil.isEmptyString(imContext.getBusinessModule().getTaskMarkPool().getFetchUserPostsTaskMark().getFilter())) {
            mFilterIcon.setImageResource(R.drawable.action_filter_filled);
        } else {
            mFilterIcon.setImageResource(R.drawable.action_filter);
        }

        mCreateUserPostCategoryView = new CreateUserPostCategoryView(this);
        mCreateUserPostCategoryView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        mRelativeLayout.addView(mCreateUserPostCategoryView);
        mCreateUserPostCategoryView.setVisibility(View.GONE);

        mAddPostButton = new ImageView(this);
        int size = (int) getResources().getDimension(R.dimen.add_post_button_size);
        int padding = (int) getResources().getDimension(R.dimen.add_post_button_padding);
        RelativeLayout.LayoutParams imageLayoutParams  = new RelativeLayout.LayoutParams(size, size);
        imageLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        imageLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mAddPostButton.setLayoutParams(imageLayoutParams);
        mAddPostButton.setPadding(padding, padding, padding, padding);
        mAddPostButton.setImageResource(R.drawable.plus);
        mAddPostButton.setScaleType(ImageView.ScaleType.FIT_XY);
        mRelativeLayout.addView(mAddPostButton);

        mAddPostButton.setOnClickListener(this);

        //去掉引导
//        if (!imContext.getSharedPrefManager().hasSeenWalkThrough(BSharedPrefManager.WALKTHOUGH_2)) {
//            Intent tutorialIntent = new Intent(this, TutorialActivity.class);
//            tutorialIntent.putExtra(TutorialActivity.TUTORIAL_EXTRA, BSharedPrefManager.WALKTHOUGH_2);
//            startActivity(tutorialIntent);
//        }
    }

    @Override
    protected void onDestroy(){
        mController.setUserPostRequestListener(null);
        super.onDestroy();
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    @OnClick(R.id.filter_icon)
    public void onFilterButtonClicked() {
        startActivityForResult(new Intent(this, UserPostFilterActivity.class), UserPostFilterActivity.FILTER_REQUEST);
    }

    @OnClick(R.id.search_icon)
    public void onSearchButtonClicked() {
        startActivity(new Intent(this, NewSearchActivity.class));
    }

    @Override
    public void onResume() {
        super.onResume();

        Tracker t = ((MainApplication) getApplication()).getTracker(MainApplication.TrackerName.APP_TRACKER);
        t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CLASSIFIEDS);
        t.send(new HitBuilders.ScreenViewBuilder().build());
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        if (exception != null) {
            Log.e(TAG, exception.getExMessage());
        }
    }

    @Override
    public void subHandleMessage(Message msg) {
        switch (msg.what) {
            case Constants.BUSINESS_STATUS_USERPOST_COMMENT_COUNT_CHANGE:
            case Constants.BUSINESS_STATUS_USER_FOLLOW:
            case Constants.BUSINESS_STATUS_USER_DELETE_FOLLOW:
                mController.flush();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UserPostFilterActivity.FILTER_REQUEST) {
            if (resultCode == RESULT_OK) {
                HashMap<String, Set<String>> chosenCategories = (HashMap<String, Set<String>>) data.getSerializableExtra(UserPostFilterActivity.SELECTED_CATEGORIES_EXTRA);
                setFilter(chosenCategories );
            }
        } else if (requestCode == CreateUserPostActivity.CREATE_POST_SUCCESS_REQUEST) {
            if (resultCode == RESULT_OK) {
                onBackPressed();
            }
        } else if (requestCode == CityNewsCommentsActivity.NEW_COMMENT_REQUEST) {
            if (resultCode == RESULT_OK) {
                String postId = data.getStringExtra("postId");
                int newCommentCount = data.getIntExtra(CityNewsCommentsActivity.NEW_COMMENT_COUNT_EXTRA, 0);
                UserPostInfo userPostInfo = imContext.getBusinessModule().getCacheManager().getUserPostsInfoCache().getItemInfoById(postId);
                if (userPostInfo != null) {
                    userPostInfo.setCommentCount(userPostInfo.getCommentCount() + newCommentCount);
                    mController.flush();
                }
            }
        }
    }

    private void setFilter(HashMap<String, Set<String>> chosenCategories) {
        if (chosenCategories != null && chosenCategories.size() > 0) {

            FilterArgs filterArgs = new FilterArgs();
            Iterator iterator = chosenCategories.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry pair = (Map.Entry)iterator.next();

                String category = (String) pair.getKey();
                Set<String> subcategories = (Set<String>) pair.getValue();

                if (category.equals("cities")) {
                    if (subcategories.size() > 0) {
                        if (subcategories.size() == 1 && subcategories.contains("")) {
                            filterArgs.setCities(null);
                        } else {
                            filterArgs.setCities(new ArrayList<String>(subcategories));
                        }
                    } else {
                        filterArgs.setCities(null);
                    }
                } else {
                    if (subcategories.size() > 0) {
                        if (subcategories.size() == 1 && subcategories.contains("")) {
                            filterArgs.getCategories().add(new FilterArgs.Category(category, null));
                        } else {
                            filterArgs.getCategories().add(new FilterArgs.Category(category, subcategories));
                        }
                    } else {
                        filterArgs.getCategories().add(new FilterArgs.Category(category, null));
                    }
                }

                iterator.remove(); // avoids a ConcurrentModificationException
            }

            mController.loadFilteredData(JSON.toJSONString(filterArgs));
            mController.onRefresh(mController);
            mFilterIcon.setImageResource(R.drawable.action_filter_filled);
        } else {
            mController.loadFilteredData(null);
            mController.onRefresh(mController);
            mFilterIcon.setImageResource(R.drawable.action_filter);
        }
    }

    public void onTopCategoryFilterSelected(String slug) {
        if (slug != null) {

            if (null != loadingViewForSwitchCategory){
                return;
            }

            mController.setUserPostRequestListener(
                    new UserPostListView.OnUserPostRequestListener() {
                        @Override
                        public void onUserPostRequestFinish() {
                            if (null != loadingViewForSwitchCategory){
                                mRelativeLayout.removeView(loadingViewForSwitchCategory);
                                loadingViewForSwitchCategory = null;
                            }
                            mController.setUserPostRequestListener(null);
                        }
                    }
            );

            loadingViewForSwitchCategory = (RelativeLayout) LayoutInflater.from(this).inflate(
                    com.pangu.ui.R.layout.mui__loading_view
                    , null);
            loadingViewForSwitchCategory.setBackgroundColor(Color.TRANSPARENT);
            RelativeLayout.LayoutParams lyParamLoading = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT
            );
            mRelativeLayout.addView(loadingViewForSwitchCategory, lyParamLoading);
            loadingViewForSwitchCategory.bringToFront();

            //
            FilterArgs filterArgs = new FilterArgs();
            filterArgs.getCategories().add(new FilterArgs.Category(slug, null));
            mController.switchFilteredData(JSON.toJSONString(filterArgs));
            mController.onRefresh(mController);
            mFilterIcon.setImageResource(R.drawable.action_filter_filled);
        } else {
            startActivityForResult(new Intent(this, UserPostFilterActivity.class), UserPostFilterActivity.FILTER_REQUEST);
        }
    }

    @Override
    public void onBackPressed() {
        if (mCreateUserPostCategoryView.getVisibility() == View.VISIBLE) {
            ViewCompat.animate(mAddPostButton)
                    .rotation(0.0F)
                    .withLayer()
                    .setDuration(500)
                    .setInterpolator(new OvershootInterpolator(5.0F))
                    .start();
            mCreateUserPostCategoryView.setVisibility(View.GONE);
            mAddPostFlag = false;
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View view) {

        if (imContext.getSharedPrefManager().getUserId() == null) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }

        if (!mAddPostFlag) {
            ViewCompat.animate(mAddPostButton)
                    .rotation(45.0F)
                    .withLayer()
                    .setDuration(500)
                    .setInterpolator(new OvershootInterpolator(5.0F))
                    .start();
            mCreateUserPostCategoryView.setVisibility(View.VISIBLE);
            mAddPostFlag = true;
        } else {
            ViewCompat.animate(mAddPostButton)
                    .rotation(0.0F)
                    .withLayer()
                    .setDuration(500)
                    .setInterpolator(new OvershootInterpolator(5.0F))
                    .start();
            mCreateUserPostCategoryView.setVisibility(View.GONE);
            mAddPostFlag = false;
        }
    }

    @Override
    public void onFilterSelected(FilterArgs filterArgs) {
        mController.loadFilteredData(JSON.toJSONString(filterArgs));
        mController.onRefresh(mController);
        mFilterIcon.setImageResource(R.drawable.action_filter_filled);
    }

    @Override
    public void onScrollUp() {

        int initPositionY = mAddPostButton.getScrollY();
        mAddPostButton.animate().cancel();
        mAddPostButton.animate().translationY(initPositionY);

        ViewPropertyAnimator viewPropertyAnimator = mToolbar.animate();
        viewPropertyAnimator.setListener(new AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mToolbar.setVisibility(View.VISIBLE);
            }
        });
        viewPropertyAnimator.translationY(0).setInterpolator(new AccelerateInterpolator()).start();
    }

    @Override
    public void onScrollDown() {

        mAddPostButton.animate().cancel();
        mAddPostButton.animate().translationYBy(350);

        ViewPropertyAnimator viewPropertyAnimator = mToolbar.animate();
        viewPropertyAnimator.setListener(new AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mToolbar.setVisibility(View.GONE);
            }
        });
        viewPropertyAnimator.translationY(-mToolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
    }
}
